package com.steven.logserver.mq;


import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * rabbitmq通用配置类
 *
 * @author qinxiaohu
 */
@Component
public class MqCommons {

    @Value("${log.netty.bind.port}")
    private Integer bindPort;

    private String addr;

    @PostConstruct
    public void init() throws UnknownHostException {

        addr = InetAddress.getLocalHost().getHostAddress().replaceAll("\\.", "") + "-" + bindPort;
    }

    public String getExchange() {

        return "exchange-" + addr;
    }

    public String getQueue() {

        return "queue-" + addr;
    }

    public String getRoutingKey() {

        return "routingKey-" + addr;
    }


    /**
     * MQ监听者Container配置
     *
     * @param container							容器
     * @param queue								队列
     * @param listener							指定的监听器
     */
    public void getContainer(SimpleMessageListenerContainer container, ChannelAwareMessageListener listener, Queue... queue){

        container.setQueues(queue);
        container.setExposeListenerChannel(true);
        // 设置最大并发的消费者数量
        container.setMaxConcurrentConsumers(10);
        // 最小的并发消费者的数量
        container.setConcurrentConsumers(1);
        // 设置确认模式为手工确认
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        // 监听器实现的MessageListener
        container.setMessageListener(listener);

    }
}
